package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.StoreTransferMapper;
import com.example.crossborderecommerce.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 调拨单货物模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/store-transfer")
public class StoreTransferController {
    @Resource
    IStoreTransferService storeTransferService;
    @Resource
    IStoreService storeService;
    @Resource
    IProductService productService;
    @Resource
    IStoreCommodityService storeCommodityService;
    @Resource
    IAdminService adminService;
    @Resource
    StoreTransferMapper storeTransferMapperr;

    /**
     * 添加调拨单
     *
     * @param storeTransfer
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody StoreTransfer storeTransfer) {
        //调出仓库货物的库存信息
        StoreCommodity storeCommodity1 = storeCommodityService.getById(storeTransfer.getTransferCommodityId());
        if (storeTransfer.getInStoreId() == storeTransfer.getOutStoreId()) {
            return Result.error("无法在仓库内部调拨！");
        } else if (storeCommodity1.getQuantity() < storeTransfer.getQuantity()) {
            return Result.error("库存不足，无法调拨！");
        } else {
            //调出后原仓库库存是否为0，调入的仓库是否有该产品
            //调入的仓库
            Store store2 = storeService.getById(storeTransfer.getInStoreId());
            //通过产品和仓库找调入仓库有没有对应的信息
            StoreCommodity storeCommodity2 = storeCommodityService.findByStoreIdProductId(store2.getId().toString(), storeCommodity1.getProductId().toString());
            if (storeCommodity2 == null) { //调入的仓库没有该产品
                //新增库存信息
                StoreCommodity newStoreCommodity = new StoreCommodity();
                newStoreCommodity.setStoreId(store2.getId());
                newStoreCommodity.setProductId(storeCommodity1.getProductId());
                newStoreCommodity.setQuantity(storeTransfer.getQuantity());
                //默认库存期望值为0.8倍
                newStoreCommodity.setMinimumQuantity((int) (storeTransfer.getQuantity() * 0.8));
                newStoreCommodity.setStatus("正常");
                storeCommodityService.saveOrUpdate(newStoreCommodity);
            } else {
                //调入的仓库增加对应货物库存
                storeCommodity2.setQuantity(storeCommodity2.getQuantity() + storeTransfer.getQuantity());
                System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                System.out.println(storeCommodity2.getQuantity());
                System.out.println(storeCommodity2.getMinimumQuantity());
                if (storeCommodity2.getQuantity() >= storeCommodity2.getMinimumQuantity()) {
                    storeCommodity2.setStatus("正常");
                }
                storeCommodityService.saveOrUpdate(storeCommodity2);
            }
            //调出的仓库减少对应货物库存
            storeCommodity1.setQuantity(storeCommodity1.getQuantity() - storeTransfer.getQuantity());
            if (storeCommodity1.getQuantity() < storeCommodity1.getMinimumQuantity()) {
                storeCommodity1.setStatus("异常");
            }
            storeCommodityService.saveOrUpdate(storeCommodity1);
            boolean res = storeTransferService.save(storeTransfer);
            if (res) {
                return Result.success("添加调拨单成功！");
            }
        }
        return Result.error("添加调拨单失败！");
    }

    /**
     * 删除调拨单
     * @param storeTransfer
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody StoreTransfer storeTransfer) {
        boolean res = storeTransferService.removeById(storeTransfer);
        if(res) {
            return Result.success("删除调拨单成功！");
        }
        return Result.error("删除调拨单失败！");
    }


    /**
     * 查询所有调拨单
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<StoreTransfer> storeTransferList = storeTransferService.list();
        if(storeTransferList != null) {
            return Result.success("查询所有调拨单成功！", storeTransferList);
        }
        return Result.error("查询所有调拨单失败！");
    }

    /**
     * 删除一系列调拨单
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> storeTransferIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = storeTransferService.removeByIds(storeTransferIds);
        if(res) {
            return Result.success("删除调拨单成功");
        }
        return Result.error("删除店调拨单失败！");
    }

    /**
     * 修改调拨单
     *
     * @param storeTransfer
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody StoreTransfer storeTransfer) { //编辑后的调拨单
        //找到之前数据库里的调拨单 13
        StoreTransfer storeTransferBefore = storeTransferService.getById(storeTransfer.getId());
        //之前调出的仓库 2
        Store storeOutBefore = storeService.getById(storeTransferBefore.getOutStoreId());
        //之前调入的仓库 3
        Store storeInBefore = storeService.getById(storeTransferBefore.getInStoreId());
        //之前调出后的仓库货物信息 6
        StoreCommodity storeCommodityOutBefore = storeCommodityService.getById(storeTransferBefore.getTransferCommodityId());
        //之前调入后的仓库货物信息 3,1 10
        StoreCommodity storeCommodityInBefore = storeCommodityService.findByStoreIdProductId(storeInBefore.getId().toString(), storeCommodityOutBefore.getProductId().toString());
        //恢复之前的库存信息（之前的库存加/减上调出去的库存）
        storeCommodityOutBefore.setQuantity(storeTransferBefore.getQuantity() + storeCommodityOutBefore.getQuantity());
        storeCommodityInBefore.setQuantity(storeCommodityInBefore.getQuantity() - storeTransferBefore.getQuantity());
        //将数据库里的信息复原
        if (storeCommodityInBefore.getQuantity() == 0) {
            storeCommodityService.removeById(storeCommodityInBefore);
        } else {
            if (storeCommodityInBefore.getQuantity() < storeCommodityInBefore.getMinimumQuantity()) {
                storeCommodityInBefore.setStatus("异常");
            } else {
                storeCommodityInBefore.setStatus("正常");
            }
            storeCommodityService.saveOrUpdate(storeCommodityInBefore);
        }
        if (storeCommodityOutBefore.getQuantity() < storeCommodityOutBefore.getMinimumQuantity()) {
            storeCommodityOutBefore.setStatus("异常");
        } else {
            storeCommodityOutBefore.setStatus("正常");
        }
        storeCommodityService.saveOrUpdate(storeCommodityOutBefore);
        //处理编辑后的调拨单
        //调出仓库货物的库存信息
        StoreCommodity storeCommodity1 = storeCommodityService.getById(storeTransfer.getTransferCommodityId());
        if (Objects.equals(storeTransfer.getInStoreId(), storeTransfer.getOutStoreId())) {
            return Result.error("无法在仓库内部调拨！");
        } else if (storeCommodity1.getQuantity() < storeTransfer.getQuantity()) {
            return Result.error("库存不足，无法调拨！");
        } else {
            //调出后原仓库库存是否为0，调入的仓库是否有该产品
            //调入的仓库
            Store store2 = storeService.getById(storeTransfer.getInStoreId());
            //通过产品和仓库找调入仓库有没有对应的信息
            StoreCommodity storeCommodity2 = storeCommodityService.findByStoreIdProductId(store2.getId().toString(), storeCommodity1.getProductId().toString());
            if (storeCommodity2 == null) { //调入的仓库没有该产品
                //新增库存信息
                StoreCommodity newStoreCommodity = new StoreCommodity();
                newStoreCommodity.setStoreId(store2.getId());
                newStoreCommodity.setProductId(storeCommodity1.getProductId());
                newStoreCommodity.setQuantity(storeTransfer.getQuantity());
                //默认库存期望值为0.8倍
                newStoreCommodity.setMinimumQuantity((int) (storeTransfer.getQuantity() * 0.8));
                newStoreCommodity.setStatus("正常");
                storeCommodityService.saveOrUpdate(newStoreCommodity);
            } else {
                //调入的仓库增加对应货物库存
                storeCommodity2.setQuantity(storeCommodity2.getQuantity() + storeTransfer.getQuantity());
                if (storeCommodity2.getQuantity() >= storeCommodity2.getMinimumQuantity()) {
                    storeCommodity2.setStatus("正常");
                }
                storeCommodityService.saveOrUpdate(storeCommodity2);
            }
            //调出的仓库减少对应货物库存
            storeCommodity1.setQuantity(storeCommodity1.getQuantity() - storeTransfer.getQuantity());
            if (storeCommodity1.getQuantity() < storeCommodity1.getMinimumQuantity()) {
                storeCommodity1.setStatus("异常");
            }
            storeCommodityService.saveOrUpdate(storeCommodity1);
            boolean res = storeTransferService.saveOrUpdate(storeTransfer);
            if (res) {
                return Result.success("修改调拨单成功！");
            }
            return Result.error("修改调拨单失败！");
        }
    }

    /**
     * 分页查询所有调拨单
     *
     * @param outStoreId
     * @param inStoreId
     * @param adminId
     * @param transferCommodityId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "-1") String outStoreId,
                           @RequestParam(defaultValue = "-1") String inStoreId,
                           @RequestParam(defaultValue = "-1") String adminId,
                           @RequestParam(defaultValue = "-1") String transferCommodityId,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<StoreTransfer> storeTransferPage = new Page<>(pageNum, pageSize);
        List<StoreTransfer> storeTransferList = storeTransferMapperr.getStoreTransferByPage(storeTransferPage,outStoreId,inStoreId,adminId,transferCommodityId);
        for(StoreTransfer storeTransfer : storeTransferList) {
            Store store=storeService.getById(storeTransfer.getOutStoreId());
            storeTransfer.setOutStoreName(store.getName());
            Store store1=storeService.getById(storeTransfer.getInStoreId());
            storeTransfer.setInStoreName(store1.getName());
            StoreCommodity storeCommodity=storeCommodityService.getById(storeTransfer.getTransferCommodityId());
            Product product=productService.getById(storeCommodity.getProductId());
            storeTransfer.setTransferCommodityName(product.getName());
            Admin admin=adminService.getById(storeTransfer.getAdminId());
            storeTransfer.setAdminName(admin.getName());

        }
        Page<StoreTransfer> newStoreTransferPage = new Page<>(pageNum, pageSize);
        newStoreTransferPage.setRecords(storeTransferList);
        newStoreTransferPage.setTotal(storeTransferPage.getTotal());
        return Result.success("成功查询所有调拨单！",newStoreTransferPage);
    }
    /**
     * 导出调拨单
     * @param outStoreId
     * @param inStoreId
     * @param adminId
     * @param transferCommodityId
     * @param response
     * @return
     */
    @GetMapping("exportStoreTransferList")
    public Result exportStoreTransferList(@RequestParam(defaultValue = "-1") String outStoreId,
                                          @RequestParam(defaultValue = "-1") String inStoreId,
                                          @RequestParam(defaultValue = "-1") String adminId,
                                          @RequestParam(defaultValue = "-1") String transferCommodityId,
                                         HttpServletResponse response) {
        QueryWrapper<StoreTransfer> queryWrapper = new QueryWrapper<>();
        List<StoreTransfer> storeTransferList = storeTransferService.list(queryWrapper);
        for(StoreTransfer storeTransfer : storeTransferList) {
            Store store=storeService.getById(storeTransfer.getOutStoreId());
            storeTransfer.setOutStoreName(store.getName());
            Store store1=storeService.getById(storeTransfer.getInStoreId());
            storeTransfer.setInStoreName(store1.getName());
            StoreCommodity storeCommodity=storeCommodityService.getById(storeTransfer.getTransferCommodityId());
            Product product=productService.getById(storeCommodity.getProductId());
            storeTransfer.setTransferCommodityName(product.getName());
            Admin admin=adminService.getById(storeTransfer.getAdminId());
            storeTransfer.setAdminName(admin.getName());

        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("出库仓库");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("调拨货物");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("调拨数量");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("入库仓库");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("调拨负责人");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("调拨时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < storeTransferList.size(); i++) {
            row = sheet.createRow(i + 1);
            StoreTransfer storeTransfer =storeTransferList.get(i);
            row.createCell((short) 0).setCellValue(storeTransfer.getId());
            row.createCell((short) 1).setCellValue(storeTransfer.getOutStoreName());
            row.createCell((short) 2).setCellValue(storeTransfer.getTransferCommodityName());
            row.createCell((short) 3).setCellValue(storeTransfer.getQuantity());
            row.createCell((short) 4).setCellValue(storeTransfer.getInStoreName());
            row.createCell((short) 5).setCellValue(storeTransfer.getAdminName());
            try {
                Date createTime = inputDateFormat.parse(storeTransfer.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 6).setCellValue(outputDateFormat.format(createTime));
            } catch (ParseException e) {
                row.createCell((short) 6).setCellValue(storeTransfer.getCreateTime().toString());
            }
        }
        String fileName = "exportStoreTransferList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportStoreTransferList");
    }
}
